package com.baizhi.cmfz.aspect;

import com.baizhi.cmfz.annottation.LogAnnottion;
import com.baizhi.cmfz.dao.CmfzLogDao;
import com.baizhi.cmfz.entity.CmfzLog;
import com.baizhi.cmfz.entity.User;
import com.baizhi.cmfz.util.IPKit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
@Aspect  //此类是一个增强类
@Configuration//声明当前类是一个配置类
public class LogAfter {
    private Logger logger=LoggerFactory.getLogger(LogAfter.class);
    @Autowired
    private CmfzLogDao cmfzLogDao;
    //后置增强  定义切入点
    @After("@annotation(com.baizhi.cmfz.annottation.LogAnnottion)")
    public  void logAfter(JoinPoint joinPoint){

        CmfzLog cmfzLog=new CmfzLog();

        //获取当前时间
        cmfzLog.setLogDate(new Date());

    //RequestContextHolder 可以获取到当前请求 当前请求对应的就是当前会话的Session
        //获取用户IP地址
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ipAddrByRequest = IPKit.getIpAddrByRequest(request);
        logger.debug(ipAddrByRequest);
        cmfzLog.setLogIp(ipAddrByRequest);
        //获取用户id
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        cmfzLog.setAdminId(user.getUserId());
      //通过连接点对象获取方法签名对象
        //通过方法签名对象获取方法对象
        //通过方法对象获取方法的注解
        //获取操作的内容
        //获取到方法的签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
       //获取的 方法对象
        Method method = signature.getMethod();
        LogAnnottion annotation = method.getAnnotation(LogAnnottion.class);
        //获取的操作内容
        String value = annotation.value();
        cmfzLog.setLogContent(value);

        //获取操作的类型
        String type = annotation.type();
        cmfzLog.setLogType(type);


        logger.debug(cmfzLog.toString());
        Integer count = cmfzLogDao.insertCmfzLog(cmfzLog);
        logger.debug(count.toString());
    }

}
